//
//  WXPFeedBackVC.m
//  MexicoLoan
//
//  Created by wxp on 2025/3/12.
//

#import "WXPFeedBackVC.h"

@interface WXPFeedBackVC ()<UITextViewDelegate>

@property (nonatomic, strong) WXPNavView * navView;

@property (nonatomic, strong) UIView * headerView;
@property (nonatomic, strong) UILabel * labelTitle;
@property (nonatomic, strong) UIView * textBackView;
@property (nonatomic, strong) UITextView * textView;
@property (nonatomic, strong) UILabel * placeholderLabel;
@property (nonatomic, strong) UILabel * numLabel;
@property (nonatomic, strong) UIButton * btnSubmit;
@property (nonatomic, assign) NSInteger maxCharacterCount;

@property (nonatomic, strong) WXPCommonAgreementView * agreementView;

@end

@implementation WXPFeedBackVC

#pragma mark - lazy
- (WXPNavView *)navView
{
    if (_navView == nil) {
        _navView = [WXPNavView new];
        [_navView resetViewWithTitle:@"Realimentación"];
        _navView.leftTop = XY(0, 0);
    }
    return  _navView;
}
- (WXPCommonAgreementView *)agreementView{
    if (!_agreementView) {
        _agreementView = [WXPCommonAgreementView new];
        _agreementView.centerXBottom = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT-LEFT_MARDIN);
    }
    return _agreementView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [UIView new];
        _headerView.userInteractionEnabled = true;
        _headerView.width = SCREEN_WIDTH-LEFT_MARDIN*2;
        [GlobalMethod setRoundView:_headerView color:[UIColor clearColor] numRound:16 width:0];
    }
    return _headerView;
}
- (UILabel *)labelTitle{
    if (!_labelTitle) {
        _labelTitle = [UILabel new];
        _labelTitle.fontNum = 12;
        _labelTitle.textColor = COLOR_BLACK;
        [_labelTitle fitTitle:@"Detalla su problema encontrado" variable:0];
    }
    return _labelTitle;
}
- (UIView *)textBackView{
    if (_textBackView == nil) {
        _textBackView = [UIView new];
        _textBackView.backgroundColor = COLOR_WHITE;
        _textBackView.widthHeight = XY(self.headerView.width-2*LEFT_MARDIN, (200));
        [GlobalMethod setRoundView:_textBackView color:COLOR_LINE numRound:16 width:1];
        
        [_textBackView addSubview:self.numLabel];
        CGFloat textViewTop = (11);
        self.textView.widthHeight = XY(self.textBackView.width-2*(12), self.numLabel.top-(12)-textViewTop);
        self.textView.leftTop = XY((12), textViewTop);
        [_textBackView addSubview:self.textView];
        self.placeholderLabel.leftTop = XY((17), (20));
        [_textBackView addSubview:self.placeholderLabel];
    }
    return _textBackView;
}
- (UITextView *)textView{
    if (!_textView) {
        _textView = [UITextView new];
        _textView.backgroundColor = COLOR_WHITE;
        _textView.delegate = self;
        _textView.font = [UIFont systemFontOfSize:(14)];
        _textView.textColor = COLOR_BLACK;
    }
    return _textView;
}
- (UILabel *)placeholderLabel{
    if (_placeholderLabel == nil) {
        _placeholderLabel = [UILabel new];
        _placeholderLabel.textColor = COLOR_LIGHT_GRAY;
        _placeholderLabel.fontNum = 12;
        [_placeholderLabel fitTitle:@"Por favor inserte" variable:(self.textView.width-2*(4))];
    }
    return _placeholderLabel;
}
- (UILabel *)numLabel{
    if (_numLabel == nil) {
        _numLabel = [UILabel new];
        _numLabel.textColor = COLOR_LIGHT_GRAY;
        _numLabel.fontNum = (12);
        [_numLabel fitTitle:[NSString stringWithFormat:@"0/%ld",self.maxCharacterCount] variable:0];
        _numLabel.rightBottom = XY(self.textBackView.width-LEFT_MARDIN, self.textBackView.height-LEFT_MARDIN);
    }
    return _numLabel;
}
- (UIButton *)btnSubmit
{
    if (_btnSubmit == nil) {
        _btnSubmit = [UIButton  new];
        _btnSubmit.backgroundColor = COLOR_PRIMARY;
        _btnSubmit.height = BUTTON_HEIGHT;
        [GlobalMethod setRoundView:_btnSubmit color:[UIColor clearColor] numRound:BUTTON_HEIGHT/2 width:0];
        [_btnSubmit setTitleColor:COLOR_BLACK forState:UIControlStateNormal];
        _btnSubmit.titleLabel.fontNum = 14;
        [_btnSubmit setTitle:@"Entregar" forState:UIControlStateNormal];
        _btnSubmit.alpha = 0.5;
        _btnSubmit.userInteractionEnabled = false;
        WEAKSELF
        [_btnSubmit setNoRepeatActionWithInterval:3 action:^(UIButton * _Nonnull button) {
            [NSObject clickFeedback];
            [weakSelf.btnSubmit addClickAnimate];
            [RequestApi requestComplaintWithTitle:@"native_feedback" content:weakSelf.textView.text delegate:weakSelf success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
                
                [GlobalMethod showAlert:@"Enviado con éxito"];
                [Global_Nav popToRootViewControllerAnimated:true];
                
            } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
                
            }];
        }];
    }
    return  _btnSubmit;
}

#pragma mark - viewDidLoad
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_Suggestion action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.maxCharacterCount = 160;
    
    UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
    [self configUI];
}

- (void)configUI{
    self.view.backgroundColor = COLOR_BACKGROUND;
    self.viewBG.backgroundColor = COLOR_BACKGROUND;
    self.tableHeaderTopBg.backgroundColor = [UIColor clearColor];
    self.tableView.backgroundColor = COLOR_WHITE;
    [self.view addSubview:self.navView];
    [self.view addSubview:self.agreementView];
    
    self.tableView.height = self.agreementView.top-10-self.navView.bottom-10;
    self.tableView.width = SCREEN_WIDTH-2*LEFT_MARDIN;
    [GlobalMethod setRoundView:self.tableView color:COLOR_WHITE numRound:16 width:0];
    self.tableView.centerXTop = XY(SCREEN_WIDTH/2, self.navView.bottom+10);
    
    self.labelTitle.leftTop = XY(LEFT_MARDIN, 18);
    [self.headerView addSubview:self.labelTitle];
    
    self.textBackView.leftTop = XY(LEFT_MARDIN, self.labelTitle.bottom+LEFT_MARDIN);
    [self.headerView addSubview:self.textBackView];
    
    self.btnSubmit.width = self.textBackView.width;
    self.btnSubmit.centerXTop = XY(self.headerView.width/2, self.textBackView.bottom+80);
    [self.headerView addSubview:self.btnSubmit];
    
    self.headerView.height = self.btnSubmit.bottom+26;
    self.tableView.tableHeaderView = self.headerView;
}

- (void)resetEnviarBtn:(BOOL)available{
    self.btnSubmit.userInteractionEnabled = available;
    self.btnSubmit.alpha = available ? 1 : 0.5;
}

#pragma mark - 收键盘
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView{
    [self.view endEditing:true];
}

- (void)tapClick:(UITapGestureRecognizer * )tap{
    [self.view endEditing:true];
}

#pragma mark - textView delegate
- (void)textViewDidChange:(UITextView *)textView{
    self.placeholderLabel.hidden = isStr(textView.text);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    // 计算输入文字的长度
    NSString * newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger markLength = newText.length;
    // 显示文字输入个数
    NSInteger textNumber = newText.length<=self.maxCharacterCount?newText.length:self.maxCharacterCount;
    [self.numLabel fitTitle:[NSString stringWithFormat:@"%ld/%ld",textNumber,self.maxCharacterCount] variable:0];
    self.numLabel.rightCenterY = XY(self.numLabel.right, self.numLabel.centerY);
    // 按钮点击状态
    [self resetEnviarBtn:isStr(newText)];
    // 截取超过最大字符数的文本
    if (newText.length > self.maxCharacterCount) {
        newText = [newText substringToIndex:self.maxCharacterCount];
        textView.text = newText;
        // 移动光标到文本的末尾
        // 延迟设置光标位置
        dispatch_async(dispatch_get_main_queue(), ^{
            UITextPosition *endPosition = [textView positionFromPosition:textView.beginningOfDocument offset:newText.length];
            UITextRange *endRange = [textView textRangeFromPosition:endPosition toPosition:endPosition];
            [textView setSelectedTextRange:endRange];
        });
    }
    // 判断文字长度是否超过限制
    return markLength <= self.maxCharacterCount;
}

- (void)moveCursorToEndOfTextView:(UITextView *)textView {
    // 获取文本的末尾位置
    UITextPosition *endPosition = [textView positionFromPosition:textView.beginningOfDocument offset:textView.text.length];
    // 创建一个新的文本范围，从末尾位置到末尾位置（即光标在末尾）
    UITextRange *endRange = [textView textRangeFromPosition:endPosition toPosition:endPosition];
    // 设置新的选择范围（光标移动到文本末尾）
    [textView setSelectedTextRange:endRange];
}

@end
